<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\Configuration;
use app\admin\model\MobileCode;
use app\admin\model\Shop;
use app\admin\model\Category;
use app\admin\model\ProductCategory;
use app\admin\model\Follow;
use app\admin\model\Noviceguide;
use app\admin\model\ChatMessage;
use app\admin\model\Product;
use app\admin\model\Prize;
use app\admin\model\PrizeUser;
use app\admin\model\ProductMessage;
use app\admin\model\ProductWish;
use app\admin\model\Community;
use app\admin\model\ConfigData;
use app\admin\model\Article;
use app\admin\model\ProductViewLog;
use app\admin\model\UserRoseLog;
use app\admin\model\UserOrder;
use app\admin\model\AreaWorldwide;
use app\admin\model\Slideshow;
use app\admin\model\Version;
use app\admin\model\TaskImg;
use app\admin\model\Area;
use app\admin\model\EventStatistics;
use app\admin\model\EventStatisticsPage;
use app\admin\model\UserStatistics;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use think\Db;
use think\Exception;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $NeedLogin = ['add_task_img']; //存在则验证token

	public function _initialize(){
		$action = request()->action();
	
		if(in_array($action,$this->NeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}

		$this->configuration = Configuration::find();
	}

	  /***
     * 生成二维码
     *
     */
    public function QRcode($url = "https://oa.yuxiang123.cn", $filename = 'createQR.png')
    {
        $writer = new PngWriter();
        //创建实例
        $qrCode = QrCode::create($url)
            ->setSize(300)
            ->setMargin(10)
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelHigh());
		//        //logo
		//        $logo = Logo::create(ROOT_PATH.'/public/static/image/qrlogo.png')->setResizeToWidth(50);
		//        //文字
		//        $label = Label::create($name);
        $result = $writer->write($qrCode);
        header('Content-Type: ' . $result->getMimeType());
        $result->saveToFile(ROOT_PATH . '/public/uploads/qrcode/' . $filename);
        return '/uploads/qrcode/' . $filename;
    }


	//新增任务截图审核
	public function add_task_img(){
		$img = $this->request->request('img');
		$type = $this->request->request('type',0);
		if(!$img){
			$this->error('参数错误');
		}
		$time =  strtotime(date('Y-m-d',time()));
		$info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>$type,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
		if($info){
			$this->error('请勿重复提交');
		}
		$data = [
			'user_id'=>$this->user['id'],
			'img'=>$img,
			'type'=>$type,
			'add_time'=>time()
		];
		TaskImg::insert($data);
		$this->success('上传成功,请等待审核');
	}

	//统计页面
	public function addEventStatisticsPage(){
		$user_id = $this->request->request('user_id',0);
		$event = $this->request->request('event','');
		$type = $this->request->request('type','xcx');
		if(!$user_id){
			return;
		}
		$arr = [
			'首页','商品详情','心愿池','心愿池详情','新手引导','活动抽奖','社区','社区详情','消息','我的','我送出的','我领取的','我发布的','搜索','我的积分','积分任务','邀请好友','地址管理','常见问题','浏览记录','我的收藏','个人中心','个人资料','确认订单','发布闲置','发布心愿','发布社区'
		];
		//判断页面是否满足
		if(!in_array($event,$arr)){
			return;
		}
		if($type != 'xcx' &&  $type != 'app'){
			return;
		}
		$info = EventStatisticsPage::where(['user_id'=>$user_id,'type'=>$type,'event'=>$event])->find();
		if($info){
			EventStatisticsPage::where(['id'=>$info['id']])->update(['sum'=>$info['sum']+1]);
		}else{
			EventStatisticsPage::insert(['type'=>$type,'event'=>$event,'user_id'=>$user_id,'sum'=>1,'add_time'=>time(),'day'=>date('Y-m-d',time())]);
		}
	}
	

	//事件埋点
	public function addEventStatistics(){
		$type = $this->request->request('type','xcx');
		$user_id = $this->request->request('user_id',0);
		$event = $this->request->request('event','');
		// if($user_id == 'o_sKy5N0XBUBqa5hrSHRxqfIq5J4'){
		// 	return;
		// }
		$arr = [
			'发布闲置','心愿页','精选（首页）','半价寄件','离我最近','最新','去白拿','新人礼包','首页banner','商品详情页','我想要','心愿页','立即兑换','发布动态','发布心愿','手机号快捷登录','积分任务-分享','确认兑换按钮','确认订单页'
		];
		$Category = ProductCategory::where(array('pid'=>1,'status'=>'normal'))->select();
		foreach ($Category as $v) {
			$arr[] = '首页分类-'.$v['name'];
		}
		//判断埋点事件是否满足
		if(!in_array($event,$arr)){
			return;
		}
		if($type != 'xcx' &&  $type != 'app'){
			return;
		}
		$where = [
			'type'=>$type,
			'events'=>$event,
			'day'=>date('Y-m-d',time())
		];
		$res = EventStatistics::where($where)->find();
		if($res){
			$update = [
				'sum'=>$res['sum']+1
			];
			if($user_id && !in_array($user_id,explode(',',$res['user_id']))){
				$update['user_id'] = $res['user_id'].','.$user_id;
			}
			EventStatistics::where(['id'=>$res['id']])->update($update);
		}else{
			$where['add_time'] = time();
			EventStatistics::insert($where);
		}
 		return;
	}
	
    public function is_ship_num(){
        $ship_num= $this->request->request('ship_num');
        if(is_ship_num($ship_num)){
            exit('ok');
        }else{
            exit('格式不支持');
        }
    }
	/*
	*发送手验证码
	*/
    public function mobile_code(){
		$mobile = $this->request->request('mobile','');
		if(empty($mobile) || !check_phone($mobile)){
            $this->error('请输入有效的手机号码');
		}else{
            $repeat=MobileCode::where(array('mobile'=>$mobile,'verify'=>0,'add_time'=>array('gt',time()-60)))->find();
            if($repeat){
                $this->error('无需重复发送');
            }
			$res = send_mobile($mobile);
			if($res['code'] == 1){
				MobileCode::insert(array('mobile'=>$mobile,'code'=>$res['code'],'verify'=>0,'add_time'=>time()));
				$this->success('发送成功');
			}else{
				$this->error($res['msg']);
			}
			// $code=rand(100000,999999);
			// //发送短信验证码，待接入
			// $configuration=$this->configuration;
			// // 注意使用GMT时间  
			// date_default_timezone_set("GMT");  
			// $target = "https://dysmsapi.aliyuncs.com/?";  
			// $accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
			// $accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
			// $ParamString="{\"code\":\"$code\"}";  
			// $data = [
			// 	'AccessKeyId' => $accessKeyId,
			// 	'Action' => 'SendSms',
			// 	'Format' => 'XML', 
			// 	'OutId' => '123', 
			// 	'PhoneNumbers' => $mobile,
			// 	'RegionId' => 'cn-hangzhou',
			// 	'SignName'=>$configuration['sign_name'],
			// 	'SignatureMethod' => 'HMAC-SHA1',
			// 	'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
			// 	'SignatureVersion' => '1.0',
			// 	'TemplateCode' => $configuration['sms_mb'], 
			// 	'TemplateParam' => $ParamString,
			// 	'Timestamp' => date("Y-m-d H:i:s"),
			// 	'Version' => '2017-05-25'
            // ];  
			// $data['Signature'] = computeSignature($data, $accessKeySecret);  
			// // 发送请求  
			// $result = xml_to_array(https_request($target.http_build_query($data)));
			// if($result['Error']['Message']){
            //     $this->error($result['Error']['Message']);
			// }else{
			// 	MobileCode::insert(array('mobile'=>$mobile,'code'=>$code,'verify'=>0,'add_time'=>time()));
            //     $this->success('发送成功');
			// }
		}
    }
	
	//获取用户的openid
	public function getOpenid($code = '',$type = ''){

		if($type){
			$res= file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=wx7e02d2ebf871c207&secret=1048ec4292504f8f4b1423b205ddb9b8&js_code='.$code.'&grant_type=authorization_code');
			$res_a=json_decode($res,true);
			if(!$res_a['openid']){
				$this->error('获取失败');
			}
			$openid=$res_a['openid'];
			return $openid;
		}else{
			$code =   $this->request->request('code');
			$token =   $this->request->request('token','');
			$login =   $this->request->request('login','');
			if($code){
				$res= file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=wx7e02d2ebf871c207&secret=1048ec4292504f8f4b1423b205ddb9b8&js_code='.$code.'&grant_type=authorization_code');
				$res_a=json_decode($res,true);
				if(!$res_a['openid']){
					$this->error('获取失败');
				}
				$openid=$res_a['openid'];
				if($token){
					$user = User::where(array('token'=>$token,'status'=>1))->find();
					if(empty($user['openid'])){
						User::where(array('id'=>$user['id']))->update(['openid'=>$openid]);
					}
				}
				if($login){ //是登录页面判断是否是新用户的操作
					//查询是否有该用户
					$user = User::where(array('openid'=>$openid,'status'=>1))->find();
					if($user){
						$this->success('获取成功',['openid'=>$openid,'mobile'=>$user['mobile']]);
					}else{
						$this->error('获取失败',$openid);
					}
				}
				
				$this->success('获取成功',$openid);
			}
		}
		
	}
	//获取经纬度
	public function get_Lat(){
		$address = $this->request->request('address');
		$this->success('操作成功',get_LonandLat($address));
	}
	public function access_token(){
		$appid ='wx7e02d2ebf871c207';
		$secret = '1048ec4292504f8f4b1423b205ddb9b8';
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$data = json_decode(file_get_contents($url,true),true);
		$access_token = $data['access_token'];
		return $access_token;
    }
	public function api_access_token(){
		$appid ='wx7e02d2ebf871c207';
		$secret = '1048ec4292504f8f4b1423b205ddb9b8';
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$data = json_decode(file_get_contents($url,true),true);
		$access_token = $data['access_token'];
		$this->success('获取成功',$access_token);
    }
	/**
     * 获取手机号
     */
    public function getPhoneNumber(){
        $code = $this->request->request('code');
		$access_token  = $this->access_token();
        $url                    = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $res = json_decode(httpRequest($url, ['code'=>$code],'json'),true);
        if(!$res || empty($res['phone_info'])){
            $this->error($res);
        }
        $phoneNumber= $res['phone_info']['phoneNumber'];
        $this->success(__('获取手机号成功'), $phoneNumber);
    }
	/*
	*登录或注册提交
	*/
	public function login(){
        $mobile = $this->request->request('mobile','');
        $openid_code = $this->request->request('openid_code','');
        $code = $this->request->request('code','');
        $cid = $this->request->request('cid','');
        $login_source = $this->request->request('login_source','xcx');
        $autocity = $this->request->request('autocity','');
        $invite_user_id = $this->request->request('invite_user_id',0);
		if((empty($mobile) || !check_phone($mobile)) && $code != 123456){
            $this->error('请输入有效的手机号码');
		}else{
			if($code == 999999){
    			//999999登录或者注册需要做统计
				MobileCode::insert(['mobile'=>$mobile,'code'=>999999,'add_time'=>time()]);
		    }elseif($code == 123456){
    			//999999登录或者注册需要做统计
				MobileCode::insert(['mobile'=>$mobile,'code'=>123456,'add_time'=>time()]);
				//查询该用户是否是任务专属用户
				$user=User::where(array('mobile'=>$mobile,'virtual_status'=>2))->find();
				if(!$user){
					$this->error('验证码错误');
				}
		    }else{
				$mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
	    		if($code!=$mobile_code['code']){
                    $this->error('验证码错误');
			    }
				
			}
			$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
			if($user){
			    $token=$user['token'];
		        if($user['status'] == 0){
                    $this->error('您的账号已被限制登陆了');
		        }
				$is_new = 0;
			}else{

				//第一次注册储存缓存 防止重复点击注册多个用户
				$redis = redis_init();
				$redis_name = 'userInfo'.$mobile;
				$info = $redis->get($redis_name);
				if(!$info){
					$redis->set($redis_name,1);
				}else{
					$this->error('请勿重复点击');
				}


				//账号注册时需要开启事务,避免出现垃圾数据
				Db::startTrans();
				try {
					//创建之前查询手机号是否已经注册
					$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
					if($user){
						Db::commit();
						$this->error('请勿重复点击');
					}

					$openid = $openid_code ? $this->getOpenid($openid_code,1) : '';
					$nickname = $this->repetition_nickname('用户'.substr($mobile,7,4));
					$token=md5(md5(date("ymdHis").rand(100000,999999)));
					$user=array(
						'mobile'			=>$mobile,
						'invite_user_id'	=>$invite_user_id,
						'rose_money'		=>0,
						'nickname'			=>$nickname,
						'avatar'			=>'https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,30).'.png',
						'profile'			=>'',
						'gender'			=>0,
						'openid'			=>$openid,
						'birthday'			=>'',
						'city'				=>'',
						'bgimg'				=>$this->configuration['default_bgimg'],
						'tags'				=>'',
						'weixin'			=>'',
						'login_source'		=> $invite_user_id ? 'new' : $login_source,
						'rose_money'		=>0,
						'read_message'		=>0,
						'follow_count'		=>0,
						'fans_count'		=>0,
						'love_count'		=>0,
						'token'				=>$token,
						'last_login_time'	=>time(),
						'add_time'			=>time()
					);
					$user_id=User::insertGetId($user);
					$user['id']=$user_id;
					if($this->configuration['register_rose_money']>0){
						//判断该用户是否是注销后的用户
						$info = User::where(['mobile'=>$mobile.'_2'])->find();
						if(!$info){
							roseandlog($user_id,$this->configuration['register_rose_money'],1,'注册奖励');
						}
					}
					if($invite_user_id>0 && $this->configuration['invite_rose_money']>0 ){
						roseandlog($invite_user_id,$this->configuration['invite_rose_money'],2,'邀请奖励');
					}

					$text = '你好，欢迎加入余享，余享是一个公益性的闲置物品分享互赠平台
					我是你的小助手大熊，有任何问题均可以私信我
					如有闲置可分享到余享送给有需要的人
					感谢你为闲置循环做出的努力！';
					$arr = [
						'content' => $text,
						'user_id' => 439,
						'js_user_id'=> $user_id,
						'add_time'=>time(),
						'is_system_chat'=>1
					];
					$arr['sort'] = $arr['js_user_id'].'00'.$arr['user_id'];
					ChatMessage::insert($arr);
					$is_new = 1; 
					Db::commit();
					$redis->set($redis_name,'');
				} catch (Exception $e) {
					Db::rollback();
					$this->error('操作失败');
				}
			}
			if($cid){
			    User::where(array('id'=>$user_id))->update(array('cid'=>$cid));
			}
			//查该用户是否是商家
			$user['shop'] = Shop::where(['user_id'=>$user['id'],'status'=>1])->find();

			$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
		}	
	}

	//检查昵称是否重复
	public function repetition_nickname($nickname,$suffix = ''){
		$user = User::where(['status'=>1,'nickname'=>$nickname.$suffix])->find();
		if($user){ // 有重复值
			if($suffix==''){
				$suffix = 'a';
			}elseif($suffix=='a'){
				$suffix = 'b';
			}elseif($suffix=='b'){
				$suffix = 'c';
			}elseif($suffix=='c'){
				$suffix = 'd';
			}
			return $this->repetition_nickname($nickname,$suffix);
		}else{
			return $nickname.$suffix;
		}
	}

    public function xcxlogin(){
        $code = $this->request->request('code');
        $openid = $this->request->request('openid','');
        $autocity = $this->request->request('autocity','');
        $invite_user_id = $this->request->request('invite_user_id',0);
        $mobile = $this->request->request('mobile');
		if(empty($mobile) || !check_phone($mobile)){
            $this->error('请输入有效的手机号码');
		}
        if($code || $openid){
            $user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
    		if($user){
	    	    $token=$user['token'];
	    	    if($user['status'] == 0){
                    $this->error('您的账号已被限制登陆了');
		        }
				$is_new = 0;
				$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
	    	}else{
				//第一次注册储存缓存 防止重复点击注册多个用户
				$redis = redis_init();
				$redis_name = 'userInfo'.$mobile;
				$info = $redis->get($redis_name);
				if(!$info){
					$redis->set($redis_name,1);
				}else{
					$this->error('请勿重复点击');
				}
				//账号注册时需要开启事务,避免出现垃圾数据
				Db::startTrans();
				try {
					//创建之前查询手机号是否已经注册
					$user=User::where(array('mobile'=>$mobile,'status'=>['in','1,0']))->find();
					if($user){
						Db::commit();
						$this->error('请勿重复点击');
					}
					$openid = $openid ? $openid : $this->getOpenid($code,1);
					$token=md5(md5(date("ymdHis").rand(100000,999999)));
					$nickname = $this->repetition_nickname('用户'.substr($mobile,7,4));
					$user['invite_user_id']	=$invite_user_id;
					$user['mobile']		    =$mobile;
					$user['rose_money']		=0;
					$user['nickname']		=$nickname;
					$user['avatar']			='https://'.$_SERVER['HTTP_HOST'].'/assets/portrait/'.rand(1,30).'.png';
					$user['profile']		='';
					$user['gender']			=0;
					$user['openid']			=$openid;
					$user['birthday']		='';
					$user['city']			='';
					$user['bgimg']			=$this->configuration['default_bgimg'];
					$user['tags']			='';
					$user['weixin'] 		='';
					$user['login_source']   = $invite_user_id ? 'new' : 'xcx';
					$user['rose_money']		=0;
					$user['read_message']	=0;
					$user['follow_count']	=0;
					$user['fans_count']		=0;
					$user['love_count']		=0;
					$user['token']			=$token;
					$user['last_login_time']=time();
					$user['add_time']		=time();
				
					$user_id=User::insertGetId($user);
					$user['id']=$user_id;
					if($this->configuration['register_rose_money']>0){
						//判断该用户是否是注销后的用户
						$info = User::where(['mobile'=>$mobile.'_2'])->find();
						if(!$info){
							roseandlog($user_id,$this->configuration['register_rose_money'],1,'注册奖励');
						}
					}
					if($invite_user_id>0 && $this->configuration['invite_rose_money']>0){
							roseandlog($invite_user_id,$this->configuration['invite_rose_money'],2,'邀请奖励');
					}
					$text = '你好，欢迎加入余享，余享是一个公益性的闲置物品分享互赠平台
					我是你的小助手大熊，有任何问题均可以私信我
					如有闲置可分享到余享送给有需要的人
					感谢你为闲置循环做出的努力！';
					$arr = [
						'content' => $text,
						'user_id' => 439,
						'js_user_id'=> $user_id,
						'add_time'=>time(),
						'is_system_chat'=>1
					];
					$arr['sort'] = $arr['js_user_id'].'00'.$arr['user_id'];
					ChatMessage::insert($arr);
					$is_new = 1;
					Db::commit();
					$redis->set($redis_name,'');
					//查该用户是否是商家
					$user['shop'] = Shop::where(['user_id'=>$user['id'],'status'=>1])->find();
					$this->success('登录成功',['token'=>$token,'user'=>$user,'is_new'=>$is_new]);
				} catch (Exception $e) {
					Db::rollback();
					$this->error('操作失败');
				}
            }
           
        }
    }
	//统计活跃
	public function add_user_statistics(){
		$openid = $this->request->request('openid','');
        $type = $this->request->request('type','');
        $brand = $this->request->request('brand','');
		if($openid){
			$where = [
				'openid'=>md5($openid),
				'day'=>date('Y-m-d',time())	
			];
			$user_statistics = UserStatistics::where($where)->find();
			if(!$user_statistics){
				$where['add_time'] = time();
				$where['type'] = $type;
				$where['brand'] = $brand;
				UserStatistics::insert($where);
			}
		}
	}
	//获取分类
	public function category(){
		$category=ProductCategory::where(array('pid'=>1,'status'=>'normal'))->order('weigh desc')->select();
		$arr = [];
		foreach($category as $a=>&$b){
			$info = Product::where(array('category_id'=>$b['id']))->find();
			if(!$info){
				unset($category[$a]);
				continue;
			}
			$b['child']=ProductCategory::where(array('pid'=>$b['id'],'status'=>'normal'))->select();
		    // for($i=0;$i<count($b['child']);$i++){
			//     $b['child'][$i]['products']=Product::where(array('category_id'=>$b['child'][$i]['id'],'status'=>1,'is_sale'=>0))->limit(0,6)->select();
		    // }
			$arr[] = $b;
		}

        $this->success('获取成功',['category'=>$arr]);
	}
	public function category_nav(){
		$category=Category::where(array('parent_id'=>0,'status'=>1))->select();
		$this->success('获取成功',['category'=>$category]);
	}
	
	//获取抽奖数据
	public function getPrizeList(){
		//检测是否开奖
		$DS = new Dingshi();
		$DS->start_prize();
		//where(['status'=>0,'start_time'=>['<=',time()]])->
		$list = Prize::order('add_time desc')->select();
		$token = $this->request->request('token','');
		$user = [];
		if($token){
			$user=User::where(array('token'=>$token))->find();
		}
		if($list){
			foreach ($list as &$v) {
				$v['images'] = explode(',',$v['image']);
				$v['prize_time'] = date('Y-m-d H:i:s',$v['prize_time']);
				$v['user_list'] = PrizeUser::alias('a')
					->field("a.*,b.avatar,b.nickname")
					->join("user b","b.id = a.user_id")
					->where(['prize_id'=>$v['id']])
					->order('a.add_time desc')
					->select();
				$v['user_count'] = count($v['user_list']);
				if($v['user_count'] > 7){
					$v['user_count'] = $v['user_count']*2 +485;
				}
				$v['is_prize'] = 0;
				$v['prize_content'] = '参与抽奖';
				$v['prize_msg'] = '';
				//如果用户登录了判断用户是否已经参与了抽奖
				if($user){
					$info = PrizeUser::where(['prize_id'=>$v['id'],'user_id'=>$user['id']])->find();
					if($info){
						$v['is_prize'] = 1;
						//判断是否已经开奖 中奖状态
						if($info['status'] == 0){ //未开奖
							$v['prize_content'] = '等待开奖中';
						}elseif($info['status'] == -1){ //未中奖
							$v['prize_content'] = '未中奖';
							$v['prize_msg'] = '很遗憾您未中奖，请关注下次抽奖时间';
						}else{
							if($info['prize_grade'] == 1){
								$men = '一';
							}elseif($info['prize_grade'] == 2){
								$men = '二';
							}elseif($info['prize_grade'] == 2){
								$men = '三';
							}
							$v['prize_content'] = $men.'等奖';
							$v['prize_msg'] = '恭喜您获得'.$men.'等奖';
						}
					}else{
						if($v['status'] == 1){
							$v['prize_content'] = '已开奖';
							$v['prize_msg'] = '已开奖，请参与下次抽奖哦';
						}
					}
				}else{
					if($v['status'] == 1){
						$v['prize_content'] = '已开奖';
						$v['prize_msg'] = '已开奖，请参与下次抽奖哦';
					}
				}
			}
		}
		$this->success('获取成功',$list);
	}
	

	//获取新手指引
	public function get_noviceguide(){
		$list = Noviceguide::select();
		$this->success('获取成功',$list);
	}
	
	public function xcx_check(){
        $flat = $this->request->request('flat');
	    if($flat!='app'){
	        $xcx_index_ad=ConfigData::where(array('name'=>'xcx_index_ad'))->value('value');
	        $xcx_index_ad_weixin=ConfigData::where(array('name'=>'xcx_index_ad_weixin'))->value('value');
		    $xcx_invite_tips=ConfigData::where(array('name'=>'xcx_invite_tips'))->value('value');
	    }else{
	        $xcx_index_ad='';
	    }
        $this->success('获取成功',['xcx_index_ad'=>$xcx_index_ad,'xcx_index_ad_weixin'=>$xcx_index_ad_weixin,'xcx_invite_tips'=>$xcx_invite_tips,'app_checking'=>1,'check'=>0]);
	}
	public function question(){
		$page = $this->request->request('page',1);
		$pagesize = $this->request->request('pagesize',20);
		$ids = $this->request->request('ids');
		$where=array('type'=>1,'status'=>1);
		if($ids){
		    $idsa=explode(',',$ids);
		    $where=array('id'=>array('in',$idsa));
		}
		$list=Article::where($where)->order('ord asc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($list as $a=>&$b){
		    $b['content']=htmlspecialchars_decode($b['content']);
		}
        $this->success('获取成功',['list'=>$list]);
	}
	public function article(){
        $id = $this->request->request('id');
		$article=Article::where(array('id'=>$id))->find();
		$article['content']=htmlspecialchars_decode($article['content']);	
		if($article){
            $this->success('获取成功',['article'=>$article]);
		}
	}
	// public function marticle(){
	// 	$id = $this->request->request('id');
	// 	$article=Article::where(array('id'=>$id))->find();
	// 	$article['content']=htmlspecialchars_decode($article['content']);	
	// 	$this->article=$article;
	// 	$this->display();
	// }
	//搜索记录
	public function search_history(){
		$keywords=[];
		//热门搜索
		$hot_search=Product::field('id,title,video_view')->where(array('is_sale'=>0,'status'=>1))->order('video_view desc')->limit(0,10)->select();
        $this->success('获取成功',['keywords'=>$keywords,'hot_search'=>$hot_search]);
	}
	public function product_view(){
        $product_id = $this->request->request('product_id',0);
	    if($product_id){
	        Product::where(array('id'=>$product_id))->setInc('video_view',1);
	        if($this->user){
	            ProductViewLog::where(array('product_id'=>$product_id,'user_id'=>$this->user['id']))->delete();
			    ProductViewLog::insert(array('product_id'=>$product_id,'user_id'=>$this->user['id'],'add_time'=>time()));

                //浏览五个视频奖励
                $today=strtotime(date("Y-m-d 00:00:00"));
                $count=ProductViewLog::where(array('user_id'=>$this->user['id'],'add_time'=>array('gt',$today)))->count();
                $reward=UserRoseLog::where(array('user_id'=>$this->user['id'],'add_time'=>array('gt',$today),'type'=>20))->find();
                if(!$reward && $count>4){
    		       // roseandlog($this->user['id'],5,20,'浏览5个视频奖励');
                }
                $this->success('操作成功',[],2);
	        }
            $this->success('操作成功');
	    }else{
            $this->error('操作失败');
	    }
	}
	public function online(){
        $chat_token = $this->request->request('chat_token');
	    if(substr($chat_token,0,3)=='C2C'){
	        $chat_token=substr($chat_token,3,strlen($chat_token)-3);
	    }
	    $now=time();
        $user=User::field('active_time,id,avatar,nickname')->where(array('token'=>$chat_token))->find();
	    if($chat_token){
	        if($now-$user['active_time']<60*10){
                $this->success('操作成功',['online'=>1,'tips'=>'您好，请问有什么可以帮到您？','user'=>$user,'title'=>$user['nickname'].' - 当前在线']);
	        }else{
                $this->success('操作成功',['online'=>0,'user'=>$user,'title'=>$user['nickname'].' - 当前不在线']);
	        }
	    }else{
    		$this->success('操作成功',['online'=>0,'user'=>$user,'title'=>$user['nickname'].' - 当前不在线']);		
	    }
	}
	public function order_message(){
	    if($this->user){
    		$product_ids=Product::where(array('user_id'=>$this->user['id']))->value('id');
    		if(count($product_ids)>0){
		    }else{
			    $product_ids=[0];
		    }
    		$mc=UserOrder::where(array('product_id'=>array('in',$product_ids),'status'=>array('in',[2,3])))->count();
    		$mr=UserOrder::where(array('user_id'=>$this->user['id'],'status'=>array('in',[2,3])))->count();
    		$order_message  =   $mc+$mr;
			$sys_unread     =ProductMessage::where(array('type'=>3,'to_user_id'=>$this->user['id'],'is_read'=>0))->count();
            $this->success('操作成功',['order_message'=>$order_message,'sys_unread'=>$sys_unread]);		
	    }else{
            $this->error('操作失败');
	    }
	}
	//别人的主页，别人的作品
	public function my_product(){
        $user_id = $this->request->request('user_id');
        $type = $this->request->request('type',1);
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
		$where = [
			'user_id'=>$user_id,
			'status'=>1,
			
		];
		if($type == 1){  
			//发布闲置
			$my_product=Product::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		}elseif($type == 2){
			//发布动态
			$my_product=Community::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		}else{
			//发布心愿
			$my_product=ProductWish::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		}
		if($my_product){
    		foreach($my_product as $a=>&$b){
				$b['user']	=User::field('id,avatar,nickname')->where(array('id'=>$b['user_id']))->find();
				$b['add_time']=timeago($b['add_time']);
				if($type == 2){
					if(!$b['imgs']){
						$b['imgs'] = 'https://oa.yuxiang123.cn/uploads/shequ.png';
					}
					$b['imgsa']=explode(',',$b['imgs']);
					$b['video_img']=$b['imgsa'][0];
					$b['title'] = $b['content'];
				}else{
					$b['imgsa']=explode(',',$b['imgs']);
					if(!$b['video_img']){
						$b['video_img']=$b['imgsa'][0];
					}
					if(strstr($b['video_img'], 'mp4')){
						$b['video_img'] = $b['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
					}
				}
    		    
	    	}
		}else{
		    $my_product=[];
		}
        $this->success('操作成功',$my_product);		
	}
	//获取当前时间戳
	public function getTime(){
		$this->success('操作成功',time());
	}
	public function slideshow(){
		$shop_site = $this->request->request('shop_site','首页');
	    $slideshow=Slideshow::where(array('position'=>1,'status'=>1,'shop_site'=>$shop_site))->select();
        $this->success('操作成功',$slideshow);		
	}
	public function upload_bg(){
	    $data=array('id'=>1,'img'=>$this->configuration['upload_bg'],'url'=>$this->configuration['upload_url']);
	    $data['bili']=80;//每秒钟80K以内，低等级别压缩
	    $data['bili_2']=3;//3M以内不压缩
	    $data['deviceBrand_list']=['huawei','Mi 10'];
        $this->success('操作成功',['data'=>$data]);		
	}
	public function version(){
		$version=Version::where(array('enforce'=>1))->order('id desc')->limit(0,1)->find();
        $this->success('操作成功',['version'=>$version]);		
	}
	public function positiontips(){
        $keyword = $this->request->request('keyword');
		$tips=file_get_contents('https://apis.map.qq.com/ws/place/v1/suggestion?keyword='.$keyword."&key=CZ2BZ-NAVHB-2PFUY-JRJF3-PD5DS-43BDC&policy=1");
		$tipa=json_decode($tips,true);
		foreach($tipa['data'] as $a=>&$b){
		    $b=array('name'=>$b['title'],'pname'=>$b['province'],'cityname'=>$b['city'],'adname'=>$b['district'],'address'=>$b['title']);
		}
        $this->success('操作成功',$tipa);		
	}
	public function autoposition(){
	    $lat=$this->request->request('latitude');
	    $lng=$this->request->request('longitude');
	    $res=json_decode(file_get_contents('https://apis.map.qq.com/ws/geocoder/v1/?location='.$lat.','.$lng.'&key=CZ2BZ-NAVHB-2PFUY-JRJF3-PD5DS-43BDC'));
	    if($res['result']['ad_info']){
            $this->error('操作失败',['address'=>$res['result']['ad_info']['province'].$res['result']['ad_info']['city']]);
	    }
	    $res=json_decode(file_get_contents('https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$lng.','.$lat.'&key=34678b013e305c23acb8e82be064b29c&radius=1000&extensions=base'),true);
	    if($res['regeocode']['formatted_address']){
            $this->success('操作成功',['address'=>$res['regeocode']['formatted_address']]);		
	    }else{
            $this->error('操作失败',['address'=>'']);
	    }
	}
	public function autocity(){
	   $lat=$this->request->request('latitude');
	   $lng=$this->request->request('longitude');
	   $area=Area::field("*,6371 * acos(
        			cos(radians('".$lat."')) * cos(radians(lat)) * cos(
        				radians(lng) - radians('".$lng."')
        			) + sin(radians('".$lat."')) * sin(radians(lat))
        		
        	) AS distance")->where(array('pid'=>array('gt',0),'level'=>2))->order('distance asc')->limit(0,1)->find();
        if($area){
            $this->success('操作成功',['area'=>$area]);
        }else{
            $this->error('位置获取失败');
        }
	}
	
	public function citylist(){
        $search_text=$this->request->request('search_text');
	    if(!empty($search_text)){
	        $cs=Area::field('id,name')->where(array('name'=>array('like','%'.$search_text.'%')))->order('id desc')->select();
	        $sf=array(
	                array(
	                    'id'=>-1,
	                    'name'=>'搜索：'.$search_text,
	                    'child'=>$cs,
	        ));
	    }else{
    	    $sf=Area::field('id,name')->where(array('pid'=>0))->order('id desc')->select();
	        foreach($sf as $a=>&$b){
	            $b['child']=Area::field('id,name')->where(array('pid'=>$b['id']))->select();
	        }
	        $remen=array(
	            'id'=>-1,
	            'name'=>'热门城市',
	            'child'=>array(
	                array('id'=>0,'name'=>'北京'),    
	                array('id'=>1,'name'=>'上海'),    
	                array('id'=>2,'name'=>'广东'),    
	                array('id'=>3,'name'=>'武汉')  
	            )
	        );
	        $sf[]=$remen;
	        $sf=array_reverse($sf);
	    }
        $this->success('操作成功',['city_list'=>$sf]);
	}
	//邀请好友分享的图片
	public function shareimg(){
        $name=$this->request->request('name');
	    $shareimg=ConfigData::where(array('name'=>$name))->value('value');
        $this->success('操作成功',['shareimg'=>$shareimg]);
	}
	// public function uni(){
    //     $mac = new \Think\Mac();
    //     echo $mac->getmac(PHP_OS);
	// }


	public function addLog(){
		$data = $this->request->request();
		db('log')->insert(['text'=>json_encode($data),'add_time'=>time()]);
	}



	//获取其他国家的省市区
	public function get_area_worldwide(){
		$country_id = $this->request->request('country_id','');
		$province = $this->request->request('province','');
		$city = $this->request->request('city','');
		if(!$country_id && !$province && !$city){
			//都没传的情况下  返回所有国家
			$arr = AreaWorldwide::field('id,name')->where(['pid'=>0,'state'=>0])->order('sort desc')->select();
		}else{
			if($country_id){
				$where = ['pid'=>$country_id];
			}elseif($province){
				$where = ['pid'=>$province];
			}elseif($city){
				$where = ['pid'=>$city];
			}
			//国家下面的省市区
			$arr = AreaWorldwide::field('id,shortname as name')->where($where)->select();
			
		}
		$this->success('操作成功',$arr);
	}




	public function getChatGpt(){
		$json_string = '[
			{"role": "user", "content": "讲一个非常搞笑软件开发案例的故事, 要有多次剧情反转,  艾思软件公司, 100字左右, www.aisisoft.cn/"}]';
		
		$TEXT = json_decode($json_string, true);
		// $text = completions($json_array);
		
		// print_r($text);
	
	
		$header = array(
			'Authorization: Bearer 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',
			'Content-type: application/json',
		);
	 
		$params = json_encode(array(
			'messages'=>$TEXT,
			'model' => 'gpt-3.5-turbo',
	 
			));
		$curl = curl_init('https://api.openai.com/v1/chat/completions');
		$options = array(
			CURLOPT_POST => true,
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_POSTFIELDS => $params,
			CURLOPT_RETURNTRANSFER => true,
		);
		curl_setopt_array($curl, $options);
		$response = curl_exec($curl);
		//var_dump($response);
		$httpcode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
		$text = "服务器连接错误,请稍后再试!";
	 
		if (200 == $httpcode || 429 == $httpcode || 401 == $httpcode || 400 == $httpcode) {
			$json_array = json_decode($response, true);
			if (isset($json_array['choices'][0]['message']['content'])) {
				$text = str_replace("\\n", "\n", $json_array['choices'][0]['message']['content']);
				// $text = $json_array;
				
			} elseif (isset($json_array['error']['message'])) {
				$text = $json_array['error']['message'];
			} else {
				$text = "对不起，我不知道该怎么回答。";
			}
		}
		var_dump($text);
	}
}
